package com.bbs.service.impl;

import com.bbs.domain.Article;
import com.bbs.domain.Upvote;
import com.bbs.mapper.ArticleMapper;
import com.bbs.mapper.UpvoteMapper;
import com.bbs.service.ArticleService;
import com.bbs.service.UpvoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

/**
 * @ClassName UpvoteServiceImpl
 * @Description TODO
 * @Author geci
 * @Date 2019/9/23 10:17
 * @Version 1.0
 */
@Service
public class UpvoteServiceImpl implements UpvoteService {

    @Autowired
    private UpvoteMapper upvoteMapper;

    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 用户点赞
     * @param articleid
     * @param isupvote 点赞状态
     * @param username
     */
    @Transactional
    @Override
    public void isUpvote(Integer articleid, Integer isupvote, String username) {

        if (articleid==null){
            return;
        }
        if (isupvote==null){
            return;
        }

        //用户点赞
        if (isupvote==1){

            //查询帖子是否点赞过
            Upvote upvote = new Upvote();
            upvote.setUpvotearticleid(articleid);
            upvote.setUpvoteusername(username);
            Upvote upvote1 = upvoteMapper.selectByPrimaryKey(upvote);
            if (upvote1.getIsupvote()==1){
                //已经点赞过
                throw new RuntimeException("5");
            }

            //修改帖子的数量
            Article article = articleMapper.selectByPrimaryKey(articleid);
            if (ObjectUtils.isEmpty(article)){
                //找不到帖子
                throw new RuntimeException("404");
            }
            article.setUpvotecount(article.getUpvotecount()+1);
            //修改点赞状态
            upvote.setIsupvote(isupvote);

            upvoteMapper.updateByPrimaryKeySelective(upvote);

        }

        //用户取消点赞点赞
        if (isupvote==0){

            //修改帖子的数量
            Article article = articleMapper.selectByPrimaryKey(articleid);
            if (ObjectUtils.isEmpty(article)){
                throw new RuntimeException("404");
            }
            article.setUpvotecount(article.getUpvotecount()-1);
            //修改点赞状态
            Upvote upvote = new Upvote();
            upvote.setUpvotearticleid(articleid);
            upvote.setIsupvote(isupvote);
            upvote.setUpvoteusername(username);
            upvoteMapper.updateByPrimaryKeySelective(upvote);
        }

    }
}
